package pkg

import (
	"fmt"
	"time"

	"github.com/dgrijalva/jwt-go"
)

const (
	APP_KEY = "www.topgoer.com"
)

// TokenHandler token加密
func TokenHandler(uid string) (string, error) {

	// 颁发一个有限期100小时的证书
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"uid": uid,
		"exp": time.Now().Add(time.Hour * time.Duration(100)).Unix(),
		"iat": time.Now().Unix(),
	})
	tokenString, err := token.SignedString([]byte(APP_KEY))
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

// GetToken token解密
func GetToken(tokenString string) (jwt.MapClaims, string) {
	//jwt.Parse()
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		return []byte(APP_KEY), nil
	})
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		fmt.Println(claims["foo"], claims["nbf"])
		return claims, ""
	} else {
		fmt.Println(err)
		return nil, "token解析失败"
	}

}
